import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:oramemo/core/config/api_config.dart';
import 'package:oramemo/core/models/api_response.dart';
import 'package:oramemo/core/network/dio_client.dart';
import 'package:oramemo/generated/json/base/json_convert_content.dart';

abstract class ApiHelper {
  static Future<T?> request<T>({
    required String path,
    DioClient? client,
    String method = 'GET',
    Map<String, dynamic>? queryParameters,
    dynamic data,
    bool isShowErrMsg = true,
    bool isShowLoading = false,
  }) async {
    try {
      if (isShowLoading) {
        showLoading();
      }
      final response = await (client ?? DioClient()).request(
        path: path,
        method: method,
        queryParameters: queryParameters,
        data: data,
      );

      ApiResponse<T?> res = ApiResponse.fromJson(
          response.data, (data) => JsonConvert.fromJsonAsT<T>(data));

      if (res.isSuccess && res.data != null) {
      } else {
        if (isShowErrMsg) {
          Toast.show(res.msg);
        }
      }
      return res.data;
    } catch (e) {
      Toast.show('网络异常');
    } finally {
      if (isShowLoading) {
        dismissLoading();
      }
    }
    return null;
  }
}
